/*
 * @Author: byAcya xiaoxianbin@4399inc.com
 * @Date: 2025-02-10 13:47:53
 * @LastEditors: byAcya xiaoxianbin@4399inc.com
 * @LastEditTime: 2025-02-21 09:43:41
 * @FilePath: \CocosFramework\assets\script\core\utils\PathUtils.ts
 * @Description:
 */
import { resources } from 'cc';
import Instance from './Instance';

export interface IPathUtils {
    extname(p: string): string; //返回拓展名
    basename(p: string, extname?: string): string; //返回文件名
    dirname(p: string): string; //返回文件所在目录
    existFile(p: string): boolean; //判断文件是否存在
}

export class PathUtils implements IPathUtils {
    public static getInstance(): PathUtils {
        return Instance.get<PathUtils>(PathUtils);
    }
    extname(p: string): string {
        const t = /(\.[^\.\/\?\\]*)(\?.*)?$/.exec(p);
        return t ? t[1] : '';
    }
    basename(p: string, extname?: string): string {
        p = p.replace(/\?.*/, '');
        const reg = /(\/|\\)([^\/\\]+)$/g;
        const result = reg.exec(p.replace(/(\/|\\)$/, ''));
        if (!result) return p;
        const base = result[2];
        if (extname && p.split('.').pop().toLowerCase() === extname.toLowerCase()) {
            return p.replace(/\.?${extname}/, '');
        }
        return base;
    }

    dirname(p: string): string {
        const t = /((.*)(\/|\\|\\\\))?(.*?\..*$)?/.exec(p);
        return t ? t[2] : '';
    }

    existFile(p: string): boolean {
        const dirname = this.dirname(p);
        const basename = this.basename(p);
        const dirWith = resources.getDirWithPath(dirname);
        return dirWith.some((item) => {
            basename == this.basename(item.path);
        });
    }
}
